package k.daniel.android.view;

import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;

/**
 * Created by daniel on 2015/8/17.
 */
public class Panel extends TableLayout {
    int numColumns = 2;
    BaseAdapter adapter;

    public int getNumColumns() {
        return numColumns;
    }

    public void setNumColumns(int numColumns) {
        this.numColumns = numColumns;
        refreshData();
    }

    Observer observer = new Observer();

    public Panel(Context context) {
        super(context);
    }

    public Panel(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    public void setAdapter(BaseAdapter adapter) {
        this.adapter = adapter;
        adapter.registerDataSetObserver(observer);
        refreshData();
    }

    private void refreshData() {
        if (adapter != null && numColumns > 0) {
            int index = 0;
            removeAllViews();
            TableRow tableRow = null;
            while (index < adapter.getCount()) {
                if (index % numColumns == 0) {
                    tableRow = new TableRow(getContext());
                    TableLayout.LayoutParams layoutParamas = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, 0);//保证上下比例是1:1
                    layoutParamas.weight = 1;
                    tableRow.setLayoutParams(layoutParamas);
                    addView(tableRow);
                }
                View item = adapter.getView(index, null, null);
                TableRow.LayoutParams layoutParamas = new TableRow.LayoutParams(0, -1);//保证左右比例为1:1，高度与父布局等高
                layoutParamas.weight = 1;
                item.setLayoutParams(layoutParamas);
                tableRow.addView(item);
                index++;
            }
        }

    }

    class Observer extends DataSetObserver {
        @Override
        public void onChanged() {
            super.onChanged();

        }

        @Override
        public void onInvalidated() {
            super.onInvalidated();
        }
    }
}
